<template>
  <div class="min-h-screen bg-gradient-to-br from-purple-50 via-indigo-50 to-blue-50">
    <!-- 导航栏 -->
    <nav class="bg-white/80 backdrop-blur-sm shadow-lg border-b border-purple-100">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <router-link to="/" class="text-xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent">
              知识图谱管理器
            </router-link>
          </div>
          <div class="flex items-center space-x-4">
            <router-link to="/" class="text-gray-600 hover:text-blue-600 transition-colors duration-200">
              首页
            </router-link>
            <router-link to="/converter" class="text-gray-600 hover:text-blue-600 transition-colors duration-200">
              转换器
            </router-link>
            <span class="text-purple-600 font-medium bg-purple-100 px-3 py-1 rounded-full">查询图谱</span>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <div class="max-w-7xl mx-auto py-2 px-4 sm:px-6 lg:px-8">
      <div class="py-2">
        <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
          <!-- 左侧：查询面板 -->
          <div class="xl:col-span-1">
            <div class="bg-white/90 backdrop-blur-sm overflow-hidden shadow-xl rounded-xl border border-purple-100">
              <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium bg-gradient-to-r from-purple-600 to-indigo-600 bg-clip-text text-transparent mb-4">
                  🔍 Cypher 查询
                </h3>
                
                <!-- Neo4j 连接配置 -->
                <div class="mb-6">
                  <h4 class="text-md font-medium bg-gradient-to-r from-green-600 to-teal-600 bg-clip-text text-transparent mb-3">🗄️ 数据库连接</h4>
                  <div class="grid grid-cols-1 gap-3">
                    <div>
                      <label class="block text-sm font-medium text-green-700">🔗 URI</label>
                      <input 
                        v-model="neo4jConfig.uri"
                        type="text" 
                        class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 text-sm" 
                        placeholder="bolt://49.235.155.102:7687"
                      >
                    </div>
                    <div class="grid grid-cols-2 gap-2">
                      <div>
                        <label class="block text-sm font-medium text-green-700">👤 用户名</label>
                        <input 
                          v-model="neo4jConfig.username"
                          type="text" 
                          class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 text-sm" 
                          placeholder="neo4j"
                        >
                      </div>
                      <div>
                        <label class="block text-sm font-medium text-green-700">🔐 密码</label>
                        <input 
                          v-model="neo4jConfig.password"
                          type="password" 
                          class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 text-sm" 
                          placeholder="密码"
                        >
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Cypher 查询输入 -->
                <div class="mb-6">
                  <label class="block text-sm font-medium text-purple-700 mb-2">📝 Cypher 查询语句</label>
                  <textarea 
                    v-model="cypherQuery"
                    rows="6"
                    class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-purple-500 focus:border-purple-500 font-mono text-sm" 
                    placeholder="MATCH (n) RETURN n LIMIT 25"
                  ></textarea>
                  <div class="mt-2 text-xs text-gray-500">
                    💡 提示：输入标准的 Cypher 查询语句
                  </div>
                </div>

                <!-- 常用查询模板 -->
                <div class="mb-6">
                  <h4 class="text-sm font-medium text-gray-700 mb-2">🎯 常用查询模板</h4>
                  <div class="space-y-2">
                    <button 
                      v-for="template in queryTemplates" 
                      :key="template.name"
                      @click="cypherQuery = template.query"
                      class="w-full text-left px-3 py-2 text-xs bg-gradient-to-r from-gray-50 to-purple-50 hover:from-purple-50 hover:to-indigo-50 border border-gray-200 rounded-lg transition-all duration-200"
                    >
                      <div class="font-medium text-purple-700">{{ template.name }}</div>
                      <div class="text-gray-600 truncate">{{ template.query }}</div>
                    </button>
                  </div>
                </div>

                <!-- 执行按钮 -->
                <button 
                  @click="executeQuery"
                  :disabled="!cypherQuery.trim() || isQuerying"
                  class="w-full bg-gradient-to-r from-purple-600 to-indigo-600 text-white px-4 py-2 rounded-lg hover:from-purple-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-105 transition-all duration-200 shadow-lg"
                >
                  <span v-if="isQuerying">🔄 查询中...</span>
                  <span v-else>🚀 执行查询</span>
                </button>
              </div>
            </div>
          </div>

          <!-- 右侧：图谱可视化和结果 -->
          <div class="xl:col-span-2 space-y-6">
            <!-- 图谱可视化区域 -->
            <div class="bg-white/90 backdrop-blur-sm overflow-hidden shadow-xl rounded-xl border border-blue-100">
              <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent mb-4">
                  🌐 图谱可视化
                </h3>
                <div class="relative w-full h-96 bg-gradient-to-br from-gray-50 to-blue-50/30 rounded-xl border border-gray-100">
                  <div 
                    ref="graphContainer"
                    class="absolute inset-0 w-full h-full"
                    :style="{ visibility: queryResult && !isQuerying ? 'visible' : 'hidden' }"
                  ></div>
                  <div v-if="!queryResult" class="absolute inset-0 flex items-center justify-center text-gray-500 text-center">
                    <div>
                      <div class="text-4xl mb-2">🔍</div>
                      <div>执行查询后将在此显示图谱</div>
                    </div>
                  </div>
                  <div v-else-if="isQuerying" class="absolute inset-0 flex items-center justify-center text-purple-600 text-center">
                    <div>
                      <div class="text-4xl mb-2">⏳</div>
                      <div>正在加载图谱...</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 查询结果表格 -->
            <div class="bg-white/90 backdrop-blur-sm overflow-hidden shadow-xl rounded-xl border border-orange-100">
              <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium bg-gradient-to-r from-orange-600 to-red-600 bg-clip-text text-transparent mb-4">
                  📊 查询结果
                </h3>
                <div class="bg-gradient-to-br from-gray-50 to-orange-50/30 rounded-xl p-4 h-64 overflow-auto border border-gray-100">
                  <div v-if="!queryResult" class="text-gray-500 text-center mt-20">
                    查询结果将在此显示
                  </div>
                  <div v-else-if="queryError" class="text-red-600 text-center mt-20">
                    <div class="text-2xl mb-2">❌</div>
                    <div class="font-medium">查询出错</div>
                    <div class="text-sm mt-2">{{ queryError }}</div>
                  </div>
                  <div v-else>
                    <!-- 统计信息 -->
                    <div class="grid grid-cols-3 gap-4 mb-4 text-sm">
                      <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-3 rounded-lg border border-blue-200">
                        <div class="font-medium text-blue-700">🔗 节点</div>
                        <div class="text-xl font-bold text-blue-600">{{ queryResult.nodes?.length || 0 }}</div>
                      </div>
                      <div class="bg-gradient-to-br from-green-50 to-green-100 p-3 rounded-lg border border-green-200">
                        <div class="font-medium text-green-700">↔️ 关系</div>
                        <div class="text-xl font-bold text-green-600">{{ queryResult.edges?.length || 0 }}</div>
                      </div>
                      <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-3 rounded-lg border border-purple-200">
                        <div class="font-medium text-purple-700">📝 记录</div>
                        <div class="text-xl font-bold text-purple-600">{{ queryResult.records?.length || 0 }}</div>
                      </div>
                    </div>
                    
                    <!-- 数据表格 -->
                    <div v-if="queryResult.records && queryResult.records.length > 0" class="overflow-x-auto">
                      <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                          <tr>
                            <th v-for="key in Object.keys(queryResult.records[0])" :key="key" class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              {{ key }}
                            </th>
                          </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                          <tr v-for="(record, index) in queryResult.records.slice(0, 10)" :key="index">
                            <td v-for="key in Object.keys(record)" :key="key" class="px-3 py-2 whitespace-nowrap text-sm text-gray-900">
                              {{ formatValue(record[key]) }}
                            </td>
                          </tr>
                        </tbody>
                      </table>
                      <div v-if="queryResult.records.length > 10" class="text-xs text-gray-500 mt-2 text-center">
                        显示前 10 条记录，共 {{ queryResult.records.length }} 条
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { Network } from 'vis-network'

// 响应式数据
const cypherQuery = ref('MATCH (n) RETURN n LIMIT 25')
const isQuerying = ref(false)
const queryResult = ref<any>(null)
const queryError = ref<string | null>(null)
const graphContainer = ref<HTMLElement>()
let network: Network | null = null

// Neo4j 配置
const neo4jConfig = ref({
  uri: 'bolt://49.235.155.102:7687',
  username: 'neo4j',
  password: '123qweasd!'
})

// 查询模板
const queryTemplates = ref([
  {
    name: '查看所有节点',
    query: 'MATCH (n) RETURN n LIMIT 25'
  },
  {
    name: '查看所有关系',
    query: 'MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 25'
  },
  {
    name: '查看主题节点',
    query: 'MATCH (n:Topic) RETURN n'
  },
  {
    name: '查看知识点',
    query: 'MATCH (n:KnowledgePoint) RETURN n LIMIT 20'
  },
  {
    name: '查看概念关系',
    query: 'MATCH (c:Concept)-[r]-(n) RETURN c, r, n LIMIT 15'
  }
])

// 执行查询
const executeQuery = async () => {
  if (!cypherQuery.value.trim()) return
  
  isQuerying.value = true
  queryError.value = null
  
  try {
    console.log('发送查询请求:', cypherQuery.value)
    
    const response = await fetch('/api/neo4j/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        cypherQuery: cypherQuery.value,
        neo4jConfig: neo4jConfig.value
      })
    })
    
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.message || '查询请求失败')
    }
    
    if (!result.success) {
      throw new Error(result.message || '查询执行失败')
    }
    
    console.log('查询成功:', result.data)
    queryResult.value = result.data
    
    // 渲染图谱
    await renderGraph()
    
  } catch (error) {
    console.error('查询失败:', error)
    queryError.value = (error as Error).message
  } finally {
    isQuerying.value = false
  }
}

// 渲染图谱（使用 vis-network）
const renderGraph = async () => {
  if (!queryResult.value) return
  
  // 确保DOM元素已经渲染
  await nextTick()
  
  if (!graphContainer.value) {
    console.error('图谱容器元素未找到')
    return
  }
  
  const { nodes, edges } = queryResult.value
  
  // 准备vis-network数据
  const visNodes = nodes.map((node: any) => ({
    id: node.id,
    label: node.label,
    group: node.group,
    title: `${node.group}: ${node.label}`,
    color: getNodeColor(node.group)
  }))
  
  const visEdges = edges.map((edge: any) => ({
    id: edge.id,
    from: edge.from,
    to: edge.to,
    label: edge.label,
    title: edge.label,
    arrows: 'to'
  }))
  
  const data = {
    nodes: visNodes,
    edges: visEdges
  }
  
  const options: any = {
    nodes: {
      shape: 'dot',
      size: 20,
      font: {
        size: 14,
        color: '#333'
      },
      borderWidth: 2,
      shadow: true
    },
    edges: {
      width: 2,
      color: { inherit: 'from' },
      smooth: {
        type: 'continuous'
      },
      font: {
        size: 12,
        align: 'middle'
      }
    },
    physics: {
      stabilization: { iterations: 100 },
      barnesHut: {
        gravitationalConstant: -8000,
        springConstant: 0.001,
        springLength: 200
      }
    },
    interaction: {
      hover: true,
      tooltipDelay: 200
    }
  }
  
  // 销毁之前的网络实例
  if (network) {
    network.destroy()
  }
  
  // 创建新的网络实例
  try {
    network = new Network(graphContainer.value, data, options)
  } catch (error) {
    console.error('创建图谱网络失败:', error)
    return
  }
  
  // 添加事件监听
  network.on('click', (params) => {
    if (params.nodes.length > 0) {
      const nodeId = params.nodes[0]
      const node = nodes.find((n: any) => n.id === nodeId)
      if (node) {
        console.log('点击节点:', node)
      }
    }
  })
}

// 根据节点类型获取颜色
const getNodeColor = (group: string) => {
  const colors: { [key: string]: string } = {
    'Topic': '#8B5CF6',
    'Concept': '#10B981', 
    'KnowledgePoint': '#F59E0B',
    'Person': '#EF4444',
    'Organization': '#3B82F6',
    'Location': '#06B6D4',
    'Event': '#EC4899',
    'Unknown': '#6B7280'
  }
  return colors[group] || colors['Unknown']
}

// 格式化显示值
const formatValue = (value: any): string => {
  if (typeof value === 'object') {
    return JSON.stringify(value)
  }
  return String(value)
}

// 组件挂载
onMounted(() => {
  console.log('GraphQueryView 组件已挂载')
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (network) {
    network.destroy()
    network = null
  }
})
</script>